﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using Website.Logger;
using DAL;
using UtilityExtensions;
using BOL.Ventas;
using BOL.UI;
using BOL.Cliente;
using BOL;
using WebLib;
using System.Web.Script.Services;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using WebLib;

namespace UILGestion.VentaAdmin.Proforma
{
    public partial class ProformaItem : System.Web.UI.UserControl
    {
        private string ORDENVENTAITEMINFO = "OrdenVentaItemInfo";

       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.IsPostBack)
            {
                WebLib.Input a = ((WebLib.Input)itemGridView.FooterRow.FindControl("descripcionEditTextBox"));
                a.ChkVal = Request.QueryString["idProyecto"];
            }
        }
        protected void CancelItem(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                itemGridView.EditIndex = -1;
                itemGridView.FooterRow.Visible = true;
                BindDataItem();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void AddItem(object sender, EventArgs e)
        {
            try
            {


                TextBox idUITXT =
                    ((TextBox)itemGridView.FooterRow.FindControl("idUITXT"));

                CheckBox bitFinanciadoCHK =
                    ((CheckBox)itemGridView.FooterRow.FindControl("bitFinanciadoCHK"));
                TextBox totalSeparacionTXT =
                    ((TextBox)itemGridView.FooterRow.FindControl("totalSeparacionTXT"));

                DAL.UI ui = DbUtil.Db.UIs.Single(p => p.idInternal == idUITXT.Text.ToInt());


                OrdenVentaItemInfo item = new OrdenVentaItemInfo(ui.idInternal,
                                                            ui.UILocalizacion.descripcion,
                                                            ui.UIBloque.descripcion,
                                                            ui.codigo,
                                                            ui.descripcion,
                                                            ui.precio,
                                                            internalID.Value.ToInt(),
                                                            ui.Moneda,
                                                            bitFinanciadoCHK.Checked,
                                                            ui.Etapa.descripcion,
                                                            totalSeparacionTXT.Text.ToDecimal().Value,
                                                            ui.Etapa.idProyecto);


                DataSet ds = (DataSet)Session[idColeccion.Value];

                ds.Tables[ORDENVENTAITEMINFO].ImportRow(Util.EntidadToDataRow(item));

                BindDataItem();
                ((ProformaEditForm)this.Page).SetEstadistica();

                //GridUpdatePanel.Update();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }


        private void LoadFromGraficoItem(int idUI)
        {

            if (idUI != 0)
            {



                DAL.UI ui = DbUtil.Db.UIs.Single(p => p.idInternal == idUI);

                OrdenVentaItemInfo item = new OrdenVentaItemInfo(ui.idInternal,
                                                            ui.UILocalizacion.descripcion,
                                                            ui.UIBloque.descripcion,
                                                            ui.codigo,
                                                            ui.descripcion,
                                                            ui.precio,
                                                            internalID.Value.ToInt(),
                                                            ui.Moneda,
                                                            false,
                                                            ui.Etapa.descripcion,
                                                            ui.montoSeparacion == 0 ? (ui.precio *Convert.ToDecimal(0.1)) : ui.montoSeparacion,
                                                            ui.Etapa.idProyecto);


                DataSet ds = (DataSet)Session[idColeccion.Value];

                ds.Tables[ORDENVENTAITEMINFO].ImportRow(Util.EntidadToDataRow(item));

                BindDataItem();
                ((ProformaEditForm)this.Page).SetEstadistica();
            }
        }



        private void LoadGraficoItem(int idUI)
        {
           
            if (idUI != 0)
            {
                DAL.UI ui = DbUtil.Db.UIs.Single(p => p.idInternal == idUI);

                TextBox idUITXT =
                    ((TextBox)itemGridView.FooterRow.FindControl("idUITXT"));

                TextBox codigoEditTextBox =
                    ((TextBox)itemGridView.FooterRow.FindControl("codigoEditTextBox"));

                TextBox descripcionEditTextBox =
                    ((TextBox)itemGridView.FooterRow.FindControl("descripcionEditTextBox"));

                TextBox descripcionEdit1TextBox =
                    ((TextBox)itemGridView.FooterRow.FindControl("descripcionEdit1TextBox"));
                TextBox totalTextBox =
                    ((TextBox)itemGridView.FooterRow.FindControl("totalTextBox"));


                TextBox totalSeparacionTXT =
                   ((TextBox)itemGridView.FooterRow.FindControl("totalSeparacionTXT"));

                TextBox localizacionEditTextBox =
                    ((TextBox)itemGridView.FooterRow.FindControl("localizacionEditTextBox"));
                TextBox pisoTextBox =
                    ((TextBox)itemGridView.FooterRow.FindControl("pisoTextBox"));
                TextBox etapaTXT =
                    ((TextBox)itemGridView.FooterRow.FindControl("etapaTXT"));

                idUITXT.Text = ui.idInternal.ToString();
                codigoEditTextBox.Text = ui.codigo;
                descripcionEditTextBox.Text = ui.descripcion;
                descripcionEdit1TextBox.Text = ui.descripcion;
                totalTextBox.Text = ui.precio.ToString();
                localizacionEditTextBox.Text = ui.UILocalizacion.descripcion;
                pisoTextBox.Text = ui.UIBloque.descripcion;
                etapaTXT.Text = ui.Etapa.descripcion;
                totalSeparacionTXT.Text = ui.montoSeparacion == 0 ? (ui.precio *Convert.ToDecimal(0.1)).ToString() : ui.montoSeparacion.ToString();

            }
        }
        protected void AddGraficoItem(object sender, EventArgs e)
        {
            try
            {
                
                 //var idUI = ProyectoPanel1.GetIDUI();

                 //LoadFromGraficoItem(idUI);
               

                
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        

        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);
                CheckBox bitFinanciadoCHK =
                    ((CheckBox)gv.Rows[e.RowIndex].FindControl("bitFinanciadoCHK"));

                TextBox idUI =
                    ((TextBox)gv.Rows[e.RowIndex].FindControl("idUITXT"));

                TextBox totalSeparacionTXT =
                    ((TextBox)gv.Rows[e.RowIndex].FindControl("totalSeparacionTXT"));

                

                DataSet ds =
                (DataSet)Session[idColeccion.Value];

                int idinternal = int.Parse(gv.DataKeys[e.RowIndex].Values[0].ToString());
                
                var item = (from a in ds.Tables[ORDENVENTAITEMINFO].AsEnumerable().Where(p => p.RowState != DataRowState.Deleted)
                            where a.Field<int>("idInternal") == idinternal
                            select a).First();

                var UIOBJ = DbUtil.Db.UIs.Single(p => p.idInternal == idUI.Text.ToInt());


                item["bitFinanciado"] = bitFinanciadoCHK.Checked;
                item["idUI"] = UIOBJ.idInternal;
                item["moneda"] = UIOBJ.Moneda;
                item["codigo"] = UIOBJ.codigo;
                item["descripcion"] = UIOBJ.descripcion;
                item["total"] = UIOBJ.precio;
                item["idOrdenVenta"] = internalID.Value.ToInt();
                item["localizacion"] = UIOBJ.UILocalizacion.descripcion;
                item["totalSeparacion"] = totalSeparacionTXT.Text.ToDecimal();

                
                item["piso"] = UIOBJ.UIBloque.descripcion;
                item["etapa"] = UIOBJ.Etapa.descripcion;
                item["totalStr"] = string.Format("{0} {1:N2}", UIOBJ.Moneda.simbol, UIOBJ.precio);

                
                Session[idColeccion.Value]=ds;
                gv.EditIndex = -1;
               
                BindDataItem();
               
                ((ProformaEditForm)this.Page).SetEstadistica();

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            try
            {
                itemGridView.EditIndex = e.NewEditIndex;
                BindDataItem();
                itemGridView.FooterRow.Visible = false;
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }



        public void Load(int idColeccion,int idParent)

        {
            this.idColeccion.Value = idColeccion.ToString();
            this.internalID.Value = idParent.ToString();
          
            BindDataItem();

        }
        public void LoadFromGrafico(int idColeccion, int idParent,int idUI)
        {
            this.idColeccion.Value = idColeccion.ToString();
            this.internalID.Value = idParent.ToString();
           
            BindDataItem();
            LoadGraficoItem(idUI);


        }
        
        protected void DeleteItem(object sender, EventArgs e)
        {
            try
            {

                ImageButton lnkRemove = (ImageButton)sender;
                int idInternal = int.Parse(lnkRemove.CommandArgument.ToString());

                DataSet ds = (DataSet)Session[idColeccion.Value];

                var drw = (from a in ds.Tables[ORDENVENTAITEMINFO].AsEnumerable().Where(p => p.RowState != DataRowState.Deleted)
                           where a.Field<int>("idInternal") == idInternal
                           select a).First();



                drw.Delete();
                //eRolList.Tables[1].Rows.Remove(drw);

                Session[idColeccion.Value.ToString()] = ds;

                BindDataItem();
                ((ProformaEditForm)this.Page).SetEstadistica();




            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        
        private void resetEmpty()
        {
            if (itemGridView.Rows.Count == 0)
            {
                List<OrdenVentaItemInfo> itemList0 = new List<OrdenVentaItemInfo>();
                OrdenVentaItemInfo itemcero = new OrdenVentaItemInfo();
                itemcero.descripcion = string.Empty;

                itemList0.Add(itemcero);
                itemGridView.DataSource = itemList0;
                itemGridView.DataBind();
                itemGridView.Rows[0].Visible = false;
            }

        }

        public void BindDataItem()
        {

            DataSet ds = (DataSet)Session[idColeccion.Value];

            itemGridView.DataSource = ds.Tables[ORDENVENTAITEMINFO];
            itemGridView.DataBind();
            resetEmpty();

        }
        protected void AddGraficaItem(object sender, EventArgs e)
        {
            try
            {


                //addItemMPOP.Show();
                //ProyectoPanel1.HideButon();
                //ProyectoPanel1.LoadMapaProyecto();
                //graficoUPNL.Update();
                ////GridUpdatePanel.Update();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        public void SoloRead()
    {
                    itemGridView.ShowFooter = false;

            
                    itemGridView.Columns[8].Visible=false;
                    itemGridView.Columns[9].Visible = false;
    }
        

    }
}